<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="add"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="update(scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="del(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件
               current-page:翻页执行回调
               @size-change 每页几条 改变执行
               total:总共多少数据
               :current-page 当前的页码
               page-size 每页显示几条
               page-sizes 自己手动选择的 每页几条数据
               layout 页面布局
               -->
              <el-pagination
                :current-page="page"
                :page-sizes="[5, 10, 20, 100]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑' : '添加'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog=false">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="hSubmit"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 分配权限弹框 -->
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogAssign"
      >
        <!-- v-if="showDialogAssign" -->
        <assign-permission ref="AssignRef" :role-id="roleId" @success="hsuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts">
import { getRoles, deleteRole, addRole, updateRole } from '@/api/setting'
import assignPermission from './assignPermission.vue'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      pagesize: 5, // 一页5条数据
      total: 0, // 总条数
      page: 1, // 当前页码
      roles: [],
      roleId: '',
      showDialog: false,
      showDialogAssign: false, // 分配权限弹框
      isEdit: false,
      roleForm: {
        description: '',
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadRoles() // 渲染数据
  },
  methods: {
    hsuccess() {
      this.showDialogAssign = false
      this.$message.success('保存角色权限成功')
    },
    // 点击分配权限
    hAssign(id) {
      this.roleId = id
      this.showDialogAssign = true

      // 组件创建完成后 重发请求获取角色所具有的权限点信息
      this.$nextTick(() => {
        this.$refs.AssignRef.loadPerById()
      })
    },
    hClose() {
      this.roleForm = { // 表单数据项
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    async loadRoles() {
      try {
        const res = await getRoles({ page: this.page, pagesize: this.pagesize })
        console.log(res.data.rows)
        this.roles = res.data.rows
        // 设置总条数
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.success('加载失败')
      }
    },

    // 切换条数时候触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.page = 1
      this.loadRoles()
    },
    // 用户点击了页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      // 切换页码 显示第一页数据
      this.loadRoles()
    },
    // 排序
    // indexMethod(index) {
    //   // console.log(index)
    //   // 点击下一页 序号连续
    //   return (this.page - 1) * this.pagesize + index + 1
    // },

    async doDel(id) {
      await deleteRole(id)
      this.$message.success('删除成功')
      if (this.roles.length === 1 && this.page > 1) {
        this.page--
      }
      // 更新数据
      this.loadRoles()
    },
    // 用户点击了删除
    del(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 确定
    hSubmit() {
      // 表单校验
      this.$refs.roleForm.validate((val) => {
        if (!val) return
        this.isEdit ? this.doUpdate() : this.doAdd()
      })
    },
    // 添加
    async doAdd() {
      try {
        // 1.发送请求 添加数据
        await addRole(this.roleForm)
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
        // 2.成功提示
        this.$message.success('添加成功')
        // 3.关闭弹窗
        this.showDialog = false
        // 4.重新渲染数据
        this.loadRoles()
      } catch (error) {
        console.log(error)
        this.$message.error('添加失败')
      }
    },

    // 点击添加
    add() {
      this.showDialog = true
      this.isEdit = false
    },
    // 修改
    update(data) {
      console.log(data, '编辑回填数据')
      // 更改状态
      this.isEdit = true
      this.showDialog = true
      // 数据回填
      this.roleForm = { ...data }
    },

    async doUpdate() {
      try {
        // 1.发送请求 添加数据
        await updateRole(this.roleForm)
        // 2.重新渲染数据
        this.loadRoles()
        // 3.成功提示
        this.$message.success('添加成功')
        // 4.关闭弹窗
        this.showDialog = false
      } catch (error) {
        console.log(error)
        this.$message.error('添加失败')
      }
    }
  }
}
</script>
